package net.dgg.rz.common.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import net.dgg.iboss.base.common.exception.BizException;
import net.dgg.iboss.base.service.CmsService;
import net.dgg.iboss.base.util.JsonUtil;
import net.dgg.iboss.base.util.http.HttpUtility;
import net.dgg.iboss.base.util.http.ResultObj;
import net.dgg.rz.common.base.service.BaseService;
import net.dgg.rz.common.constant.ScProductConstant;
import net.dgg.rz.common.constant.SystemCommonConstant;
import net.dgg.rz.common.excption.CommonExcption;
import net.dgg.rz.common.files.entity.Annex;
import net.dgg.rz.common.files.service.AnnexService;
import net.dgg.rz.common.systemRecord.entity.SystemRecord;
import net.dgg.rz.common.systemRecord.service.SystemRecordService;
import net.dgg.rz.common.utils.DataPermissionUtils;
import net.dgg.rz.common.utils.SearchUtils;
import net.dgg.rz.common.utils.StringUtils;
import net.dgg.rz.common.utils.ValidateUtils;
import net.dgg.rz.production.entity.ProductOrder;
import net.dgg.rz.production.exception.ProductOrderExcption;
import net.dgg.tmd.foundation.platform.org.dao.OrgRecorderDAO;
import net.dgg.tmd.foundation.platform.org.entity.OrganizationDTO;
import net.dgg.tmd.foundation.platform.org.service.OrganizationManager;
import net.dgg.tmd.foundation.platform.session.SessionManager;
import net.dgg.tmd.foundation.platform.user.entity.UserDTO;
import net.dgg.tmd.foundation.platform.user.entity.UserEntity;
import net.dgg.tmd.foundation.platform.user.service.UserService;
import net.dgg.utils.http.DggHttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 公用Service
 */
@Service
public class CommonService extends BaseService {
    @Autowired
    private UserService userService;
    @Autowired
    private SessionManager sessionManager;
    @Autowired
    private OrganizationManager organizationManager;
    @Autowired
    private OrgRecorderDAO orgRecorderDAO;
    @Autowired
    private CmsService cmsService;
    @Autowired
    private SearchUtils searchUtils;
    @Value("${cmsBaseUrl}")
    private String cmsBaseUrl;
    @Value("${orfApiUrl}")
    private String orfApiUrl;
    @Autowired
    DataPermissionUtils dataPermissionUtils;
    @Autowired
    AnnexService annexService;
    @Value("${dgg.oss[0].bucket-uri}")
    private String fastdfsHost;
    @Autowired
    SystemRecordService systemRecordService;
    @Value("${ibosschan}")
    private String ibosschan;
    @Value("${productApi}")
    private String productApi;
    @Value("${dgg.tac.microuag.domain}")
    private String baseUrl;
    @Value("${dgg.appId}")
    private String sysCode;
    @Value("${dgg.secretKey}")
    private String secret;


    /**
     * 查询字典接口
     *
     * @param code   编码
     * @param status 状态 1：启用，0：禁用，无：所有
     * @param type   1：根据分类编码查询下级第一级分类（用于Select选择）
     *               2：根据分类编码查询所有下级分类（用于Tree选择无父级的）
     *               3：根据分类编码查询所有下级分类包含自己（用于Tree选择有父级的）
     * @return
     */
    public List<Map> queryTreeBook(String code, Integer status, Integer type, Integer level) {
        List<Map> treeBooks = cmsService.getTreeBookList(code, status, type, level);
        return treeBooks;
    }


    /**
     * 用户息查询
     *
     * @param params
     * @return
     */
    public List<UserDTO> findUserDTOList(Map params) {
        if (params.get("orgIds") != null) {
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(Long.parseLong(params.get("orgIds").toString()));
            params.put("orgIds", listIds);
        }
        // 用户信息选择类型
        String type = "all";// 默认:全部用户，division：当前登录人所在事业部，department:当前登录人所在部门及以下
        if (StringUtils.isNotEmpty(params.get("type"))) {
            type = params.get("type").toString();
        }
        if ("division".equals(type)) {
            UserEntity userEntity = sessionManager.getCurrentUser();
            OrganizationDTO organ = organizationManager.findOrgParentByLevel(userEntity.getOrgId(), "ORG_LEVEL_1");
            if (null != organ) {
                List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(organ.getId());
                params.put("orgIds", listIds);
            }
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {//事业部下的角色
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        } else if ("department".equals(type)) {
            UserEntity userEntity = sessionManager.getCurrentUser();
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(userEntity.getOrgId());
            params.put("orgIds", listIds);
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {//当前部门下的角色
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        } else if ("role".equals(type)) {
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        }

        // 判断是否选择了部门查询条件
        if (StringUtils.isNotEmpty(params.get("organId"))) {
            Long organId = Long.parseLong(params.get("organId").toString());
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(organId);
            if (null != listIds && listIds.size() > 0) {
                params.put("orgIds", listIds);
            }
        }
        // 判断是否分页查询
        if (StringUtils.isNotEmpty(params.get("length")) && StringUtils.isNotEmpty(params.get("start"))) {
            Integer count = userService.findUserCount(params);
            params.put("count", count);
            Integer limit = Integer.parseInt(params.get("length").toString());
            Integer start = Integer.parseInt(params.get("start").toString());
            params.put("limit", limit);
            params.put("start", start);
        }

        List<UserDTO> userList = userService.findUserDTOPage(params);
        return userList;
    }

    /**
     * 查询用户所在事业部
     *
     * @param user
     * @return
     */
    public Long findUserSyb(UserEntity user) {
        Long sybId = organizationManager.findOrgParentIdByIdAndOrgLevel(user.getOrgId(), "ORG_LEVEL_1");
        ValidateUtils.isTrue(StringUtils.isNotEmpty(sybId), CommonExcption.class, "该用户组织机构没有所在事业部");
        return sybId;
    }

    /**
     * 根据条件查询所有部门
     *
     * @param params ｛
     *               type: 部门查询类型
     *               all:全部部门，division：当前登录人所在事业部下所有部门，department:当前登录人所在部门下所有部门
     *               ｝
     * @return
     */
    public List<Map<String, Object>> findParamsOrgan(Map params) {
        Long organId = 1L;
        String type = "all";// all:全部部门，division：当前登录人所在事业部下所有部门，department:当前登录人所在部门下所有部门
        if (StringUtils.isNotEmpty(params.get("type"))) {
            type = params.get("type").toString();
        }
        if ("division".equals(type)) {
            UserEntity userEntity = sessionManager.getCurrentUser();
            OrganizationDTO organ = organizationManager.findOrgParentByLevel(userEntity.getOrgId(), "ORG_LEVEL_1");
            if (null != organ) {
                organId = organ.getId();
            }
        } else if ("department".equals(type)) {
            UserEntity userEntity = sessionManager.getCurrentUser();
            organId = userEntity.getOrgId();
        }
        params.put("orgId", organId);
        params.put("enabled", 1);
        params.remove("type");
        List<OrganizationDTO> organList = organizationManager.findOrgChlidsPage(params);
        List<Map<String, Object>> list = new ArrayList<>();
        for (OrganizationDTO org : organList) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", org.getId());
            map.put("name", org.getName());
            map.put("parentId", org.getpId());
            list.add(map);
        }
        return list;
    }

    /*
     * @Author zsx
     * @Date 2018-09-03 11:09:13
     * @Description  查询资质审核拥有权限的人
     * @param roleCode 权限code
     * @return  List<UserDTO>
     */
    public Set<UserEntity> findUserByOrgAndRole() {
        UserEntity userEntity = sessionManager.getCurrentUser();
        OrganizationDTO organ = organizationManager.findOrgParentByLevel(userEntity.getOrgId(), "ORG_LEVEL_1");
        //ValidateUtils.strNotEmpty(organ, CertificateExcption.class, "当前登录人未查询到组织架构");
        List<Long> orgIds = organizationManager.findOrgIdByAncestorId(organ.getId());
        orgIds.add(organ.getId());
        Set<UserEntity> users = new HashSet<>();
        users.addAll(userService.findUserByOrgAndRole(orgIds, "ZZSC_ZZ_ADMIN"));
        users.addAll(userService.findUserByOrgAndRole(orgIds, "ZZSC_ZZ_SUPER_ADMIN"));
        return users;
    }

    /**
     * 翻译指定code
     *
     * @param codes
     * @return
     */
    public List<Map> getTreeBookObjMulti(String codes) {
        return cmsService.getTreeBookObjMulti(codes);
    }


    /**
     * 2018年6月14日 16:30:09
     * 修改  先计算预计完结时间 再按自然日 顺延 暂停总时长
     *
     * @param start
     * @param len
     * @param suspendMiniSec
     * @return
     */
    public Date getWorkDateFrom(Date start, Integer len, Long suspendMiniSec) {
        Date date = this.getWorkDateFrom(start, len);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MILLISECOND, suspendMiniSec.intValue());
        return calendar.getTime();
    }

    /**
     * 获取从某日开始x个工作日的日期
     *
     * @param start 开始日期
     * @param len   天数
     * @return
     */
    public Date getWorkDateFrom(Date start, Integer len) {
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(start);
        Map map = new HashMap();
        map.put("date", fmt.format(start));
        map.put("days", len);
        String dateStr = this.cmsService.findAfterDate(fmt.format(start), len);
        Assert.hasText(dateStr, "获取工作日失败！");
        Date date = null;
        try {
            date = fmt.parse(dateStr);
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(date);
            calendar1.set(Calendar.HOUR_OF_DAY, calendarStart.get(Calendar.HOUR_OF_DAY));
            calendar1.set(Calendar.MINUTE, calendarStart.get(Calendar.MINUTE));
            calendar1.set(Calendar.SECOND, calendarStart.get(Calendar.SECOND));
            calendar1.set(Calendar.MILLISECOND, calendarStart.get(Calendar.MILLISECOND));
            return calendar1.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
            ValidateUtils.isTrue(false, ProductOrderExcption.class, "工作日期转换出现异常");
        }
        return date;
    }


    /**
     * 获取代入暂停时间后的 从某日开始x个工作日的日期
     *
     * @param start          开始日期
     * @param len            天数
     * @param suspendMiniSec 暂停时长 单位: 毫秒
     * @return
     */
    private Date getDateFrom(Date start, Integer len, Long suspendMiniSec) {
        Calendar calendarStart = Calendar.getInstance();
        calendarStart.setTime(start);
        Calendar overCalendar = Calendar.getInstance();
        overCalendar.setTime(start);
        overCalendar.add(Calendar.DAY_OF_YEAR, len);
        overCalendar.add(Calendar.MILLISECOND, suspendMiniSec.intValue());
        return overCalendar.getTime();
    }

    /**
     * 计算日期 存在暂停时间时
     *
     * @param start          开始时间
     * @param len            天数
     * @param suspendMiniSec 暂停时长 ：毫秒
     * @param dateType       类型，常量定义于 WorkDayOrNaturalDayStatus
     * @return
     */
    public Date getDateFromStartByType(Date start, Integer len, Long suspendMiniSec, int dateType) {
        return ScProductConstant.WORKDAY_STATUS == dateType ?
                this.getWorkDateFrom(start, len, suspendMiniSec) : this.getDateFrom(start, len, suspendMiniSec);
    }


    /**
     * 翻译城市代码
     *
     * @param code
     * @return
     */
    public String translateCityCode(@RequestParam String code) {
        String codes = "";
        Map treeBookObj = cmsService.getTreeBookObj(code);

        // 如果上级不包含全国
        if (!SystemCommonConstant.NATIONWIDE.equals(treeBookObj.get("pcode"))) {
            Map parentTreeBook = cmsService.getTreeBookObj(treeBookObj.get("pcode").toString());
            codes += parentTreeBook.get("name").toString() + "/";
        }
        codes += treeBookObj.get("name").toString();
        return codes;
    }


    /**
     * <p>@Description 异步推送消息</p>
     * <p>@author mqy</p>
     *
     * @param userEntityList 推送消息的对象
     * @param msg            消息内容
     * @param templateCode   消息模板的code
     *                       <p>@Time 2018/9/14 0014 9:40 创建时间</p>
     *                       <p>@return</p>
     */
    public void sendMsgByAsynchronous(List<UserEntity> userEntityList, String[] msg, String templateCode) {
        //给他整个名字
        ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("send-msg-pool-%d").build();
        //核心线程一个,最大四个,五秒回收,多余的排队
        ThreadPoolExecutor executor = new ThreadPoolExecutor(1, 4,
                5, TimeUnit.SECONDS, new SynchronousQueue<>(), threadFactory);
        //这里使用了 lambda 表达式
        executor.execute(() -> {
            for (UserEntity sendUser : userEntityList) {
                cmsService.sendMessage(sendUser.getId(), 1L, msg, templateCode, 1);
            }
        });
    }

    /**
     * @return true 不可以  false 可以
     * @Author Quanlin Wan
     * @Description //TODO 判断是否可以新增或者修改产品（融资）
     * @Date 19:40 2019/3/26
     * @Param orderId 销售主订单id
     **/
    public boolean findFinanceOrderId(Long orderId) {
        boolean res = true;
        Map params = new HashMap();
        params.put("orderId", orderId);
        try {
            String bas = HttpUtility.postRest(orfApiUrl + SystemCommonConstant.ABLETOCHANGORADD, params);
            ResultObj resultObj = JsonUtil.json2Obj(bas, ResultObj.class);
            if (resultObj.getCode() == 0) {
                boolean orderRes = "false".equals(resultObj.getData())?true:false;
                return orderRes;
            }else {
                res = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 根据商品属性id查询渠道
     * @Date 17:54 2019/3/27
     * @Param
     **/

    public List<Map> findChannelsByGoodsId(Long goodsId) {
        ValidateUtils.strNotEmpty(goodsId, ProductOrderExcption.class, "商品属性ID不能为空");
        List<Map> reList = new ArrayList<>();
        Map params = new HashMap();
        params.put("goodsId", goodsId);
        try {
            String bas = HttpUtility.postRest(cmsBaseUrl + SystemCommonConstant.FINDCHANNELBYGOODSID, params);
            ResultObj resultObj = JsonUtil.json2Obj(bas, ResultObj.class);
            if (resultObj.getCode() == 0) {
                reList = JsonUtil.json2List(resultObj.getData(), Map.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reList;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 新增、更新生产单时同步销售子订单数据至iboss
     * @Date 19:40 2019/3/26
     * @Param params 销售主订单id
     **/
    public void updateBusOrder(String busOrderJson) throws IOException {
        Map params = new HashMap();
        params.put("orderBusiness", busOrderJson);
        String bas = null;
        bas = HttpUtility.postRest(orfApiUrl + SystemCommonConstant.UPDATEBUSORDER, params);
        ValidateUtils.strNotEmpty(bas, ProductOrderExcption.class, "推送至订单系统失败");
        ResultObj resultObj = JsonUtil.json2Obj(bas, ResultObj.class);
        ValidateUtils.isTrue(resultObj.getCode() != 1, ProductOrderExcption.class, resultObj.getMsg());
        ValidateUtils.isTrue(resultObj.getCode() == 0, ProductOrderExcption.class, "推送至订单系统失败");
    }

    /**
     * APP 用户息查询
     *
     * @param params
     * @return
     */
    public List<UserDTO> findUserDTOListForApp(Map params) {
        if (params.get("orgIds") != null) {
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(Long.parseLong(params.get("orgIds").toString()));
            params.put("orgIds", listIds);
        }
        // 用户信息选择类型
        String type = "all";// 默认:全部用户，division：当前登录人所在事业部，department:当前登录人所在部门及以下
        if (StringUtils.isNotEmpty(params.get("type"))) {
            type = params.get("type").toString();
        }
        if ("division".equals(type)) {
            ValidateUtils.strNotEmpty(params.get("userLoginName"), ProductOrderExcption.class, "未获取到登录人，请重新登录");
            UserEntity userEntity = searchUtils.getcurrUser(params);
            OrganizationDTO organ = organizationManager.findOrgParentByLevel(userEntity.getOrgId(), "ORG_LEVEL_1");
            if (null != organ) {
                List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(organ.getId());
                params.put("orgIds", listIds);
            }
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {//事业部下的角色
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        } else if ("department".equals(type)) {
            UserEntity userEntity = sessionManager.getCurrentUser();
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(userEntity.getOrgId());
            params.put("orgIds", listIds);
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {//当前部门下的角色
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        } else if ("role".equals(type)) {
            if (StringUtils.isNotEmpty(params.get("roleCode"))) {
                List<Long> userIds = userService.findUserByRoleCode(params.get("roleCode").toString());
                params.put("userIds", userIds);
            }
        }

        // 判断是否选择了部门查询条件
        if (StringUtils.isNotEmpty(params.get("organId"))) {
            Long organId = Long.parseLong(params.get("organId").toString());
            List<Long> listIds = orgRecorderDAO.findOrgIdsByPId(organId);
            if (null != listIds && listIds.size() > 0) {
                params.put("orgIds", listIds);
            }
        }
        // 判断是否分页查询
        if (StringUtils.isNotEmpty(params.get("length")) && StringUtils.isNotEmpty(params.get("start"))) {
            Integer count = userService.findUserCount(params);
            params.put("count", count);
            Integer limit = Integer.parseInt(params.get("length").toString());
            Integer start = Integer.parseInt(params.get("start").toString());
            params.put("limit", limit);
            params.put("start", start);
        }
        //判断是否有查询条件,不能确定传递过来的参数是realName还是loginName，所以查询两次
        if (StringUtils.isNotEmpty(params.get("searchKey"))) {
            params.put("realName", params.get("searchKey"));
            List<UserDTO> userList1 = userService.findUserDTOPage(params);
            params.remove("realName");
            params.put("loginName", params.get("searchKey"));
            List<UserDTO> userList2 = userService.findUserDTOPage(params);
            userList2.addAll(userList1);
            return userList2;
        }

        List<UserDTO> userList = userService.findUserDTOPage(params);
        return userList;
    }


    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO APP上传接口，可适用pc端
     * @Date 16:48 2019/4/23
     * @Param
     **/
    public Annex uploadFile(String scProductOrderId, MultipartFile file, String userLoginName) {
        //融资生产系统没有多个文件的情况,默认为true
         String isOne = "true";
         ProductOrder productOrder= dataPermissionUtils.uoloadFileDataAccess(scProductOrderId, userLoginName);
         UserEntity userEntity=searchUtils.getcurrUser(new HashMap(){{
             put("userLoginName", userLoginName);
         }});

        if (null == file) {
            throw new ProductOrderExcption("文件不能为空");
        }
        long fileSize = file.getSize();
        if (fileSize > (20 * 1024 * 1024)) {
            throw new ProductOrderExcption("文件不能超过20MB");
        }

        String customerId = String.valueOf(productOrder.getCustomerId());
        ValidateUtils.strNotEmpty(customerId, ProductOrderExcption.class, "客户id为空，数据异常");
        StringBuffer fileId = new StringBuffer();
        fileId.append(customerId);
        fileId.append("-");
        fileId.append(SystemCommonConstant.FILE_CODE);
        fileId.append("-");
        fileId.append(scProductOrderId);
        ValidateUtils.strNotEmpty(fileId, ProductOrderExcption.class, "参数异常");
        String fileStr=String.valueOf(fileId);
        //如果一个类型的附件，只能上传一个，就先查询原来的附件，然后进行删除
        if (!StringUtils.isEmpty(isOne) && "true".equals(isOne)) {
            List<Annex> files = annexService.findFile(fileStr);
            if (null != files) {
                for (Annex m : files) {
                    //删除原来的附件
                    annexService.delFile(fileStr, m.getFilename());
                }
            }
        }

        //进行上传
        Annex item = annexService.saveMultipartFile(fileStr, file);
        // 保存操作日志
        SystemRecord systemRecord = new SystemRecord();
        systemRecord.setSource("5");
        systemRecord.setOperateType("1");
        systemRecord.setWorkId(1L);
        systemRecord.setWorkTableName("annex");
        systemRecord.setRemarks("上传文件：" + item.getFileid() + ":" + item.getFilename());
        systemRecordService.apiSave(systemRecord,userEntity);
        return item;
    }

    /**
     * @Author Quanlin Wan
     * @Description 渠道列表(新)
     * @Date 14:44 2019/7/12
     * @Param [proId]
     * @return java.util.List<java.util.Map>
     **/
    public List<Map> channelByProid(String proId) {
        List<Map> reList = new ArrayList<>();
        try {
            if (net.dgg.iboss.base.util.StringUtils.isEmpty(proId)) {
                throw new BizException("产品ID不能为空");
            }
            //由于修改直接传入业态代价太大，所以先通过产品id查询当前产品的大业态
            Map params = new HashMap();
            params.put("proId", proId);
            Map productInfo = getProductInfo(Long.parseLong(proId));
            String busYt = ScProductConstant.BUS_YT_DK;
            if(productInfo!=null){
                busYt = productInfo.get("productTypeParent")==null?ScProductConstant.BUS_YT_DK:productInfo.get("productTypeParent").toString();
            }
            params.put("typeCode",busYt);
            String resultStr = HttpUtility.postRest(ibosschan + SystemCommonConstant.CHANNEL_BY_YT, params);
            ResultObj resultObj = JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 == resultObj.getCode()) {
                reList = JsonUtil.json2List(resultObj.getData(), Map.class);
            } else {
                throw new BizException(resultObj.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reList;
    }

    /**
     * @return
     * @Author Quanlin Wan
     * @Description //TODO 根据商品属性id查询渠道(新)
     * @Date 17:54 2019/3/27
     * @Param
     **/
    public List<Map> findChannelsByGoodsIdNew(Long goodsId) {
        ValidateUtils.strNotEmpty(goodsId, ProductOrderExcption.class, "商品属性ID不能为空");
        List<Map> reList = new ArrayList<>();
        Map params = new HashMap();
        params.put("goodsId", goodsId);
        try {
            String bas = HttpUtility.postRest(ibosschan + SystemCommonConstant.CHANNEL_BY_GOODSID_URL, params);
            ResultObj resultObj = JsonUtil.json2Obj(bas, ResultObj.class);
            if (resultObj.getCode() == 0) {
                reList = JsonUtil.json2List(resultObj.getData(), Map.class);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reList;
    }

    /**
     * @Author zyou
     * @Description 根据渠道id查询渠道
     * @Date 14:44 2019/7/12
     * @Param [proId]
     * @return java.util.List<java.util.Map>
     **/
    public List<Map> channelById(Long channelIds) {
        List<Map> reList = new ArrayList<>();
        try {
            if (channelIds == null) {
                throw new BizException("渠道ID不能为空");
            }

            Map params = new HashMap();
            params.put("channelIds", channelIds);
            String resultStr = HttpUtility.postRest(ibosschan + SystemCommonConstant.CHANNEL_BY_CHANNEL_ID, params);
            ResultObj resultObj = JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 == resultObj.getCode()) {
                reList = JsonUtil.json2List(resultObj.getData(), Map.class);
            } else {
                throw new BizException(resultObj.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reList;
    }

    /**
     * 通过产品id去产品中心换取serialId
     * @param businessProductId
     * @return
     */
    public Long getSerialId(Long businessProductId){
        //通过产品id去产品中心换取serialId
        if(businessProductId==null){
            return businessProductId;
        }
        Map product = getProductInfo(businessProductId);
        if(product != null){
            businessProductId = product.get(SystemCommonConstant.SERIAL_ID)==null?businessProductId:Long.parseLong(product.get(SystemCommonConstant.SERIAL_ID).toString());
        }
        return businessProductId;
    }


    /**
     * 根据产品id查询产品信息（此id为新产品中心id，未经过转换的）
     * @param productId
     * @return
     */
    public Map getProductInfo(Long productId){
        Map reMap = new HashMap();
        try {
            if (null == productId) {
                throw new BizException("产品ID不能为空");
            }
            Map params = new HashMap();
            params.put("id",productId);
            String resultStr = HttpUtility.postRest(productApi + SystemCommonConstant.GET_PRODUCT_V3, params);
            ResultObj resultObj = JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 == resultObj.getCode()) {
                reMap = JsonUtil.json2Obj(resultObj.getData(), Map.class);
            } else {
                throw new BizException(resultObj.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reMap;
    }


    /**
     * 新产品中心产品列表
     *
     * @return
     */
    public List<Map> searchProduct(Map params) {
        List<Map> reList = new ArrayList<>();
        try {
            String resultStr = HttpUtility.postRest(productApi + SystemCommonConstant.SEARCH_PRODUCT_V3, params);
            ResultObj resultObj = JsonUtil.json2Obj(resultStr, ResultObj.class);
            if (0 == resultObj.getCode()) {
                if(resultObj.getData()!=null){
                    Map map = JsonUtil.json2Obj(resultObj.getData(),Map.class);
                    if(map != null && map.get("data") != null){
                        reList = JsonUtil.json2List(JsonUtil.obj2Json(map.get("data")), Map.class);
                    }
                }
            } else {
                throw new BizException(resultObj.getMsg());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return reList;
    }


    /**
     * 发送短信方法
     * @param phones                手机号，可以个手机号用,分隔
     * @param msgTemplateId         短信模板id
     * @param contentParamMap       模板中变量，key为变量名，value为变量值
     * @param title                 短信标题
     * @param recverType            0-内部用户，1-外部用户
     * @return
     */
    public Map sendSMS(String phones, String msgTemplateId, Map contentParamMap, String title, Integer recverType){
        String json = "[\n" +
                "    {\n" +
                "        \"syscode\": \""+ sysCode +"\",\n" +
                "        \"msgTemplateId\": \""+ msgTemplateId  +"\",\n" +
                "        \"contentParamMap\": {\n";
        if(StringUtils.isNotEmpty(contentParamMap)){
            Set<String> set =contentParamMap.keySet();
            for(String key : set){
                json += "            \"" + key + "\": \"" + contentParamMap.get(key) + "\",\n";
            }
        }
        json +=         "        },\n" +
                        "        \"recverMap\": {\n" +
                        "            \"SMS\": {\n" +
                        "                \"contact\": \"" + phones + "\"\n" +
                        "            }\n" +
                        "        },\n" +
                        "        \"recverName\": \"客户\",\n" +
                        "        \"recverType\": "+ recverType + ",\n" +
                        "        \"senderName\": \"系统\",\n" +
                        "        \"title\": \"" + title + "\"\n" +
                        "    }\n" +
                        "]";
        JSONArray reqParam = JSON.parseArray(json);
        String result = DggHttpUtil.doPostObjectByGateway(
                baseUrl + SystemCommonConstant.SEND_NEWS,
                sysCode,
                secret,
                null, reqParam, null);
        if(StringUtils.isNotEmpty(result)) {
            Map map = JsonUtil.json2Obj(result, Map.class);
            return map;
        }
        return null;
    }
}



